<template>
  <div class="system-settings-bg">
    <div class="system-settings-center">
      <!-- 页面标题区域 -->
      <div class="settings-header">
        <div class="settings-avatar">
          <i class="el-icon-setting"></i>
        </div>
        <div class="settings-title">系统设置</div>
        <div class="settings-subtitle">管理系统基本配置和参数</div>
      </div>

      <!-- 权限检查提示 -->
      <div v-if="!isAdmin" class="permission-alert">
        <el-alert
          title="权限不足"
          description="只有管理员可以修改系统设置，您当前只有查看权限"
          type="warning"
          show-icon
          :closable="false"
        />
      </div>

      <!-- 系统设置区域 -->
      <div class="settings-management">
        <el-tabs v-model="activeTab" class="settings-tabs">
          <!-- 基本设置 -->
          <el-tab-pane label="基本设置" name="basic">
            <div class="tab-content">
              <el-form
                ref="basicForm"
                :model="basicSettings"
                :rules="basicRules"
                label-width="120px"
                class="settings-form"
              >
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="系统名称" prop="systemName">
                      <el-input
                        v-model="basicSettings.systemName"
                        placeholder="请输入系统名称"
                        :disabled="!isAdmin"
                        maxlength="50"
                        show-word-limit
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="系统版本" prop="systemVersion">
                      <el-input
                        v-model="basicSettings.systemVersion"
                        placeholder="请输入系统版本"
                        :disabled="!isAdmin"
                        maxlength="20"
                        show-word-limit
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="管理员邮箱" prop="adminEmail">
                      <el-input
                        v-model="basicSettings.adminEmail"
                        placeholder="请输入管理员邮箱"
                        :disabled="!isAdmin"
                        type="email"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="系统语言" prop="systemLanguage">
                      <el-select
                        v-model="basicSettings.systemLanguage"
                        placeholder="请选择系统语言"
                        :disabled="!isAdmin"
                        style="width: 100%"
                      >
                        <el-option label="简体中文" value="zh-CN" />
                        <el-option label="English" value="en-US" />
                        <el-option label="日本語" value="ja-JP" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="时区设置" prop="timezone">
                      <el-select
                        v-model="basicSettings.timezone"
                        placeholder="请选择时区"
                        :disabled="!isAdmin"
                        style="width: 100%"
                      >
                        <el-option label="UTC+8 (北京时间)" value="Asia/Shanghai" />
                        <el-option label="UTC+0 (格林威治时间)" value="UTC" />
                        <el-option label="UTC-8 (太平洋时间)" value="America/Los_Angeles" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="日期格式" prop="dateFormat">
                      <el-select
                        v-model="basicSettings.dateFormat"
                        placeholder="请选择日期格式"
                        :disabled="!isAdmin"
                        style="width: 100%"
                      >
                        <el-option label="YYYY-MM-DD" value="YYYY-MM-DD" />
                        <el-option label="MM/DD/YYYY" value="MM/DD/YYYY" />
                        <el-option label="DD/MM/YYYY" value="DD/MM/YYYY" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-form-item label="系统描述" prop="systemDescription">
                  <el-input
                    v-model="basicSettings.systemDescription"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入系统描述"
                    :disabled="!isAdmin"
                    maxlength="200"
                    show-word-limit
                  />
                </el-form-item>

                <el-form-item>
                  <el-button
                    type="primary"
                    @click="saveBasicSettings"
                    :loading="savingBasic"
                    :disabled="!isAdmin"
                  >
                    <el-icon><Check /></el-icon>
                    保存基本设置
                  </el-button>
                  <el-button @click="resetBasicSettings" :disabled="!isAdmin">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>

          <!-- 安全设置 -->
          <el-tab-pane label="安全设置" name="security">
            <div class="tab-content">
              <el-form
                ref="securityForm"
                :model="securitySettings"
                :rules="securityRules"
                label-width="120px"
                class="settings-form"
              >
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="密码最小长度" prop="minPasswordLength">
                      <el-input-number
                        v-model="securitySettings.minPasswordLength"
                        :min="6"
                        :max="20"
                        :disabled="!isAdmin"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="密码过期天数" prop="passwordExpireDays">
                      <el-input-number
                        v-model="securitySettings.passwordExpireDays"
                        :min="0"
                        :max="365"
                        :disabled="!isAdmin"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="登录失败锁定" prop="loginFailLock">
                      <el-switch
                        v-model="securitySettings.loginFailLock"
                        :disabled="!isAdmin"
                        active-text="启用"
                        inactive-text="禁用"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="锁定阈值" prop="lockThreshold">
                      <el-input-number
                        v-model="securitySettings.lockThreshold"
                        :min="3"
                        :max="10"
                        :disabled="!isAdmin || !securitySettings.loginFailLock"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="会话超时时间" prop="sessionTimeout">
                      <el-input-number
                        v-model="securitySettings.sessionTimeout"
                        :min="10"
                        :max="480"
                        :disabled="!isAdmin"
                        style="width: 100%"
                      />
                      <span class="unit-text">分钟</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="强制HTTPS" prop="forceHttps">
                      <el-switch
                        v-model="securitySettings.forceHttps"
                        :disabled="!isAdmin"
                        active-text="启用"
                        inactive-text="禁用"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-form-item label="IP白名单" prop="ipWhitelist">
                  <el-input
                    v-model="securitySettings.ipWhitelist"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入IP白名单，每行一个IP地址"
                    :disabled="!isAdmin"
                  />
                </el-form-item>

                <el-form-item>
                  <el-button
                    type="primary"
                    @click="saveSecuritySettings"
                    :loading="savingSecurity"
                    :disabled="!isAdmin"
                  >
                    <el-icon><Check /></el-icon>
                    保存安全设置
                  </el-button>
                  <el-button @click="resetSecuritySettings" :disabled="!isAdmin">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>

          <!-- 邮件设置 -->
          <el-tab-pane label="邮件设置" name="email">
            <div class="tab-content">
              <el-form
                ref="emailForm"
                :model="emailSettings"
                :rules="emailRules"
                label-width="120px"
                class="settings-form"
              >
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="SMTP服务器" prop="smtpServer">
                      <el-input
                        v-model="emailSettings.smtpServer"
                        placeholder="请输入SMTP服务器地址"
                        :disabled="!isAdmin"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="SMTP端口" prop="smtpPort">
                      <el-input-number
                        v-model="emailSettings.smtpPort"
                        :min="1"
                        :max="65535"
                        :disabled="!isAdmin"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="邮箱账号" prop="emailAccount">
                      <el-input
                        v-model="emailSettings.emailAccount"
                        placeholder="请输入邮箱账号"
                        :disabled="!isAdmin"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="邮箱密码" prop="emailPassword">
                      <el-input
                        v-model="emailSettings.emailPassword"
                        type="password"
                        placeholder="请输入邮箱密码"
                        :disabled="!isAdmin"
                        show-password
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="发件人名称" prop="senderName">
                      <el-input
                        v-model="emailSettings.senderName"
                        placeholder="请输入发件人名称"
                        :disabled="!isAdmin"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="启用SSL" prop="enableSsl">
                      <el-switch
                        v-model="emailSettings.enableSsl"
                        :disabled="!isAdmin"
                        active-text="启用"
                        inactive-text="禁用"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-form-item>
                  <el-button
                    type="primary"
                    @click="saveEmailSettings"
                    :loading="savingEmail"
                    :disabled="!isAdmin"
                  >
                    <el-icon><Check /></el-icon>
                    保存邮件设置
                  </el-button>
                  <el-button @click="testEmailSettings" :disabled="!isAdmin">
                    <el-icon><Message /></el-icon>
                    测试邮件
                  </el-button>
                  <el-button @click="resetEmailSettings" :disabled="!isAdmin">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>

          <!-- 日志设置 -->
          <el-tab-pane label="日志设置" name="logging">
            <div class="tab-content">
              <el-form
                ref="loggingForm"
                :model="loggingSettings"
                :rules="loggingRules"
                label-width="120px"
                class="settings-form"
              >
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="日志级别" prop="logLevel">
                      <el-select
                        v-model="loggingSettings.logLevel"
                        placeholder="请选择日志级别"
                        :disabled="!isAdmin"
                        style="width: 100%"
                      >
                        <el-option label="DEBUG" value="debug" />
                        <el-option label="INFO" value="info" />
                        <el-option label="WARN" value="warn" />
                        <el-option label="ERROR" value="error" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="日志保留天数" prop="logRetentionDays">
                      <el-input-number
                        v-model="loggingSettings.logRetentionDays"
                        :min="1"
                        :max="365"
                        :disabled="!isAdmin"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="启用操作日志" prop="enableOperationLog">
                      <el-switch
                        v-model="loggingSettings.enableOperationLog"
                        :disabled="!isAdmin"
                        active-text="启用"
                        inactive-text="禁用"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="启用登录日志" prop="enableLoginLog">
                      <el-switch
                        v-model="loggingSettings.enableLoginLog"
                        :disabled="!isAdmin"
                        active-text="启用"
                        inactive-text="禁用"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-form-item label="日志文件路径" prop="logFilePath">
                  <el-input
                    v-model="loggingSettings.logFilePath"
                    placeholder="请输入日志文件路径"
                    :disabled="!isAdmin"
                  />
                </el-form-item>

                <el-form-item>
                  <el-button
                    type="primary"
                    @click="saveLoggingSettings"
                    :loading="savingLogging"
                    :disabled="!isAdmin"
                  >
                    <el-icon><Check /></el-icon>
                    保存日志设置
                  </el-button>
                  <el-button @click="clearLogs" :disabled="!isAdmin">
                    <el-icon><Delete /></el-icon>
                    清空日志
                  </el-button>
                  <el-button @click="resetLoggingSettings" :disabled="!isAdmin">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>

          <!-- 配置变更日志 -->
          <el-tab-pane label="配置变更日志" name="change-log">
            <div class="tab-content">
              <div class="log-header">
                <h4>配置变更记录</h4>
                <div class="log-actions">
                  <el-input
                    v-model="searchKeyword"
                    placeholder="搜索变更记录"
                    style="width: 200px"
                    clearable
                  >
                    <template #prefix>
                      <el-icon><Search /></el-icon>
                    </template>
                  </el-input>
                  <el-button type="primary" @click="refreshChangeLog">
                    <el-icon><Refresh /></el-icon>
                    刷新
                  </el-button>
                </div>
              </div>

              <el-table
                :data="filteredChangeLog"
                border
                style="width: 100%"
                :loading="loadingChangeLog"
              >
                <el-table-column prop="timestamp" label="变更时间" width="180">
                  <template #default="scope">
                    {{ formatDateTime(scope.row.timestamp) }}
                  </template>
                </el-table-column>
                <el-table-column prop="operator" label="操作人" width="120" />
                <el-table-column prop="module" label="配置模块" width="120" />
                <el-table-column prop="action" label="操作类型" width="100">
                  <template #default="scope">
                    <el-tag
                      :type="getActionType(scope.row.action)"
                      size="small"
                    >
                      {{ scope.row.action }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="变更描述" />
                <el-table-column prop="ip" label="IP地址" width="120" />
                <el-table-column label="操作" width="100" fixed="right">
                  <template #default="scope">
                    <el-button
                      type="primary"
                      size="small"
                      @click="viewChangeDetail(scope.row)"
                    >
                      详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <div class="pagination-container">
                <el-pagination
                  v-model:current-page="currentPage"
                  v-model:page-size="pageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  :total="total"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 变更详情弹窗 -->
    <el-dialog
      v-model="changeDetailVisible"
      title="变更详情"
      width="600px"
      class="change-detail-dialog"
    >
      <div v-if="selectedChangeLog" class="change-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="变更时间">
            {{ formatDateTime(selectedChangeLog.timestamp) }}
          </el-descriptions-item>
          <el-descriptions-item label="操作人">
            {{ selectedChangeLog.operator }}
          </el-descriptions-item>
          <el-descriptions-item label="配置模块">
            {{ selectedChangeLog.module }}
          </el-descriptions-item>
          <el-descriptions-item label="操作类型">
            <el-tag :type="getActionType(selectedChangeLog.action)" size="small">
              {{ selectedChangeLog.action }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="IP地址">
            {{ selectedChangeLog.ip }}
          </el-descriptions-item>
          <el-descriptions-item label="用户代理">
            {{ selectedChangeLog.userAgent }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="change-content">
          <h5>变更内容</h5>
          <el-card class="change-card">
            <div class="change-item">
              <strong>变更前：</strong>
              <pre>{{ selectedChangeLog.beforeValue }}</pre>
            </div>
            <div class="change-item">
              <strong>变更后：</strong>
              <pre>{{ selectedChangeLog.afterValue }}</pre>
            </div>
          </el-card>
        </div>

        <div class="change-description">
          <h5>变更描述</h5>
          <p>{{ selectedChangeLog.description }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Check, Refresh, Message, Delete, Search,
  Setting, Lock, Document, Warning
} from '@element-plus/icons-vue'

console.log('SystemSettings组件已加载')

// 响应式数据
const activeTab = ref('basic')
const isAdmin = ref(true) // 模拟当前用户是管理员
const searchKeyword = ref('')
const loadingChangeLog = ref(false)
const changeDetailVisible = ref(false)
const selectedChangeLog = ref(null)

// 保存状态
const savingBasic = ref(false)
const savingSecurity = ref(false)
const savingEmail = ref(false)
const savingLogging = ref(false)

// 表单引用
const basicForm = ref(null)
const securityForm = ref(null)
const emailForm = ref(null)
const loggingForm = ref(null)

// 基本设置
const basicSettings = reactive({
  systemName: '通用管理系统',
  systemVersion: 'v1.0.0',
  adminEmail: 'admin@example.com',
  systemLanguage: 'zh-CN',
  timezone: 'Asia/Shanghai',
  dateFormat: 'YYYY-MM-DD',
  systemDescription: '这是一个功能完善的通用管理系统，支持用户管理、权限控制、内容管理等功能。'
})

// 安全设置
const securitySettings = reactive({
  minPasswordLength: 8,
  passwordExpireDays: 90,
  loginFailLock: true,
  lockThreshold: 5,
  sessionTimeout: 30,
  forceHttps: true,
  ipWhitelist: '192.168.1.1\n192.168.1.2\n127.0.0.1'
})

// 邮件设置
const emailSettings = reactive({
  smtpServer: 'smtp.example.com',
  smtpPort: 587,
  emailAccount: 'noreply@example.com',
  emailPassword: 'password123',
  senderName: '系统管理员',
  enableSsl: true
})

// 日志设置
const loggingSettings = reactive({
  logLevel: 'info',
  logRetentionDays: 30,
  enableOperationLog: true,
  enableLoginLog: true,
  logFilePath: '/var/log/system/'
})

// 表单验证规则
const basicRules = {
  systemName: [
    { required: true, message: '请输入系统名称', trigger: 'blur' },
    { min: 2, max: 50, message: '系统名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  systemVersion: [
    { required: true, message: '请输入系统版本', trigger: 'blur' }
  ],
  adminEmail: [
    { required: true, message: '请输入管理员邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

const securityRules = {
  minPasswordLength: [
    { required: true, message: '请输入密码最小长度', trigger: 'blur' }
  ],
  passwordExpireDays: [
    { required: true, message: '请输入密码过期天数', trigger: 'blur' }
  ],
  lockThreshold: [
    { required: true, message: '请输入锁定阈值', trigger: 'blur' }
  ],
  sessionTimeout: [
    { required: true, message: '请输入会话超时时间', trigger: 'blur' }
  ]
}

const emailRules = {
  smtpServer: [
    { required: true, message: '请输入SMTP服务器', trigger: 'blur' }
  ],
  smtpPort: [
    { required: true, message: '请输入SMTP端口', trigger: 'blur' }
  ],
  emailAccount: [
    { required: true, message: '请输入邮箱账号', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  emailPassword: [
    { required: true, message: '请输入邮箱密码', trigger: 'blur' }
  ]
}

const loggingRules = {
  logLevel: [
    { required: true, message: '请选择日志级别', trigger: 'change' }
  ],
  logRetentionDays: [
    { required: true, message: '请输入日志保留天数', trigger: 'blur' }
  ],
  logFilePath: [
    { required: true, message: '请输入日志文件路径', trigger: 'blur' }
  ]
}

// 配置变更日志
const changeLog = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 过滤后的变更日志
const filteredChangeLog = computed(() => {
  if (!searchKeyword.value) {
    return changeLog.value
  }
  return changeLog.value.filter(log => 
    log.operator.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
    log.module.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
    log.description.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 保存基本设置
const saveBasicSettings = async () => {
  if (!basicForm.value) return
  
  try {
    const valid = await basicForm.value.validate()
    if (valid) {
      savingBasic.value = true
      
      // 模拟保存
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 记录变更日志
      addChangeLog('基本设置', '修改', '更新系统基本配置信息')
      
      ElMessage.success('基本设置保存成功！')
    }
  } catch (error) {
    ElMessage.error('保存失败，请检查输入信息')
  } finally {
    savingBasic.value = false
  }
}

// 重置基本设置
const resetBasicSettings = () => {
  basicForm.value?.resetFields()
  ElMessage.info('已重置基本设置')
}

// 保存安全设置
const saveSecuritySettings = async () => {
  if (!securityForm.value) return
  
  try {
    const valid = await securityForm.value.validate()
    if (valid) {
      savingSecurity.value = true
      
      // 模拟保存
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 记录变更日志
      addChangeLog('安全设置', '修改', '更新系统安全配置')
      
      ElMessage.success('安全设置保存成功！')
    }
  } catch (error) {
    ElMessage.error('保存失败，请检查输入信息')
  } finally {
    savingSecurity.value = false
  }
}

// 重置安全设置
const resetSecuritySettings = () => {
  securityForm.value?.resetFields()
  ElMessage.info('已重置安全设置')
}

// 保存邮件设置
const saveEmailSettings = async () => {
  if (!emailForm.value) return
  
  try {
    const valid = await emailForm.value.validate()
    if (valid) {
      savingEmail.value = true
      
      // 模拟保存
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 记录变更日志
      addChangeLog('邮件设置', '修改', '更新邮件服务器配置')
      
      ElMessage.success('邮件设置保存成功！')
    }
  } catch (error) {
    ElMessage.error('保存失败，请检查输入信息')
  } finally {
    savingEmail.value = false
  }
}

// 测试邮件设置
const testEmailSettings = async () => {
  if (!emailForm.value) return
  
  try {
    const valid = await emailForm.value.validate()
    if (valid) {
      ElMessage.info('正在发送测试邮件...')
      
      // 模拟发送测试邮件
      await new Promise(resolve => setTimeout(resolve, 2000))
      
      ElMessage.success('测试邮件发送成功！')
    }
  } catch (error) {
    ElMessage.error('测试邮件发送失败')
  }
}

// 重置邮件设置
const resetEmailSettings = () => {
  emailForm.value?.resetFields()
  ElMessage.info('已重置邮件设置')
}

// 保存日志设置
const saveLoggingSettings = async () => {
  if (!loggingForm.value) return
  
  try {
    const valid = await loggingForm.value.validate()
    if (valid) {
      savingLogging.value = true
      
      // 模拟保存
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 记录变更日志
      addChangeLog('日志设置', '修改', '更新系统日志配置')
      
      ElMessage.success('日志设置保存成功！')
    }
  } catch (error) {
    ElMessage.error('保存失败，请检查输入信息')
  } finally {
    savingLogging.value = false
  }
}

// 清空日志
const clearLogs = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有日志吗？此操作不可恢复！',
      '清空日志确认',
      {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    ElMessage.info('正在清空日志...')
    
    // 模拟清空日志
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 记录变更日志
    addChangeLog('日志设置', '清空', '清空所有系统日志')
    
    ElMessage.success('日志清空成功！')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('清空日志失败')
    }
  }
}

// 重置日志设置
const resetLoggingSettings = () => {
  loggingForm.value?.resetFields()
  ElMessage.info('已重置日志设置')
}

// 添加变更日志
const addChangeLog = (module, action, description) => {
  const log = {
    id: Date.now(),
    timestamp: new Date(),
    operator: '管理员',
    module,
    action,
    description,
    ip: '192.168.1.100',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    beforeValue: '旧配置值',
    afterValue: '新配置值'
  }
  
  changeLog.value.unshift(log)
  total.value = changeLog.value.length
}

// 刷新变更日志
const refreshChangeLog = async () => {
  loadingChangeLog.value = true
  try {
    // 模拟加载数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟变更日志数据
    changeLog.value = [
      {
        id: 1,
        timestamp: new Date('2024-01-15 10:30:00'),
        operator: '管理员',
        module: '基本设置',
        action: '修改',
        description: '更新系统名称和版本信息',
        ip: '192.168.1.100',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        beforeValue: '旧系统名称',
        afterValue: '通用管理系统'
      },
      {
        id: 2,
        timestamp: new Date('2024-01-14 15:20:00'),
        operator: '管理员',
        module: '安全设置',
        action: '修改',
        description: '调整密码策略和安全配置',
        ip: '192.168.1.100',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        beforeValue: '密码最小长度: 6',
        afterValue: '密码最小长度: 8'
      },
      {
        id: 3,
        timestamp: new Date('2024-01-13 09:15:00'),
        operator: '管理员',
        module: '邮件设置',
        action: '修改',
        description: '配置邮件服务器参数',
        ip: '192.168.1.100',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        beforeValue: 'SMTP服务器: 未配置',
        afterValue: 'SMTP服务器: smtp.example.com'
      },
      {
        id: 4,
        timestamp: new Date('2024-01-12 14:45:00'),
        operator: '管理员',
        module: '日志设置',
        action: '修改',
        description: '调整日志级别和保留策略',
        ip: '192.168.1.100',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        beforeValue: '日志级别: debug',
        afterValue: '日志级别: info'
      }
    ]
    
    total.value = changeLog.value.length
  } catch (error) {
    ElMessage.error('加载变更日志失败')
  } finally {
    loadingChangeLog.value = false
  }
}

// 查看变更详情
const viewChangeDetail = (log) => {
  selectedChangeLog.value = log
  changeDetailVisible.value = true
}

// 格式化日期时间
const formatDateTime = (date) => {
  return new Date(date).toLocaleString('zh-CN')
}

// 获取操作类型标签样式
const getActionType = (action) => {
  const types = {
    '修改': 'primary',
    '新增': 'success',
    '删除': 'danger',
    '清空': 'warning'
  }
  return types[action] || 'info'
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 模拟初始数据
onMounted(async () => {
  console.log('SystemSettings组件已挂载')
  
  // 加载变更日志
  await refreshChangeLog()
})
</script>

<style scoped>
.system-settings-bg {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  width: 100vw;
  height: 100vh;
  background: #fff;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  overflow-y: auto;
  z-index: 999;
}

.system-settings-center {
  width: 100%;
  max-width: 1400px;
  background: transparent;
  border-radius: 0;
  padding: 40px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 auto;
}

.settings-header {
  text-align: center;
  margin-bottom: 40px;
}

.settings-avatar {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 30px;
  font-size: 32px;
  color: white;
  box-shadow: 0 15px 30px rgba(102, 126, 234, 0.3);
}

.settings-title {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 8px;
}

.settings-subtitle {
  color: #7f8c8d;
  font-size: 16px;
  margin: 0;
}

.permission-alert {
  width: 100%;
  max-width: 1400px;
  margin-bottom: 20px;
}

.settings-management {
  width: 100%;
  max-width: 1400px;
}

.settings-tabs {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  background: white;
}

.tab-content {
  padding: 20px;
}

.settings-form {
  max-width: 800px;
}

.unit-text {
  margin-left: 10px;
  color: #7f8c8d;
  font-size: 14px;
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.log-header h4 {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
}

.log-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.change-detail-dialog {
  border-radius: 16px;
}

.change-detail {
  padding: 20px 0;
}

.change-content {
  margin: 20px 0;
}

.change-content h5 {
  margin-bottom: 10px;
  color: #2c3e50;
  font-size: 16px;
}

.change-card {
  background: #f8f9fa;
  border: 1px solid #e1e8ed;
}

.change-item {
  margin-bottom: 15px;
}

.change-item:last-child {
  margin-bottom: 0;
}

.change-item strong {
  color: #2c3e50;
  display: block;
  margin-bottom: 5px;
}

.change-item pre {
  background: white;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #e1e8ed;
  margin: 0;
  font-size: 12px;
  color: #606266;
  white-space: pre-wrap;
  word-break: break-all;
}

.change-description {
  margin-top: 20px;
}

.change-description h5 {
  margin-bottom: 10px;
  color: #2c3e50;
  font-size: 16px;
}

.change-description p {
  color: #606266;
  line-height: 1.6;
  margin: 0;
}

/* 深度样式修改 */
:deep(.el-tabs__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  margin: 0;
  border-bottom: none;
}

:deep(.el-tabs__nav) {
  border: none;
}

:deep(.el-tabs__item) {
  color: white !important;
  font-weight: 600;
  font-size: 14px;
  padding: 0 20px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  transition: all 0.3s ease;
}

:deep(.el-tabs__item:hover) {
  color: #fff !important;
  background: rgba(255, 255, 255, 0.1);
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

:deep(.el-tabs__item.is-active) {
  color: #fff !important;
  background: rgba(255, 255, 255, 0.2);
  font-weight: 700;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

:deep(.el-tabs__active-bar) {
  background-color: white;
  height: 3px;
}

:deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
}

:deep(.el-tabs__content) {
  padding: 0;
}

:deep(.el-input__wrapper) {
  border-radius: 12px;
  border: 2px solid #e1e8ed;
  background: #f8f9fa;
  transition: all 0.3s ease;
  min-height: 48px;
}

:deep(.el-input__wrapper:hover) {
  border-color: #667eea;
  background: white;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  background: white;
}

:deep(.el-textarea__inner) {
  border-radius: 12px;
  border: 2px solid #e1e8ed;
  background: #f8f9fa;
  transition: all 0.3s ease;
}

:deep(.el-textarea__inner:hover) {
  border-color: #667eea;
  background: white;
}

:deep(.el-textarea__inner:focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  background: white;
}

:deep(.el-select), :deep(.el-input-number) {
  width: 100%;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #2c3e50;
}

:deep(.el-switch) {
  margin-top: 5px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .system-settings-center {
    padding: 30px 15px;
    max-width: 95vw;
  }
  
  .settings-title {
    font-size: 28px;
  }
  
  .settings-avatar {
    width: 70px;
    height: 70px;
    font-size: 28px;
  }
  
  .settings-form {
    max-width: 100%;
  }
  
  .log-header {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
  
  .log-actions {
    justify-content: flex-end;
  }
}

@media (max-width: 600px) {
  .system-settings-center {
    padding: 20px 10px;
    max-width: 100vw;
  }
  
  .settings-title {
    font-size: 24px;
  }
  
  .settings-avatar {
    width: 60px;
    height: 60px;
    font-size: 24px;
  }
  
  .tab-content {
    padding: 15px;
  }
  
  .log-actions {
    flex-direction: column;
    align-items: stretch;
  }
}

@media (max-width: 480px) {
  .system-settings-center {
    padding: 15px 8px;
    max-width: 100vw;
  }
  
  .settings-title {
    font-size: 20px;
  }
  
  .settings-avatar {
    width: 50px;
    height: 50px;
    font-size: 20px;
  }
  
  .tab-content {
    padding: 10px;
  }
  
  .settings-form {
    font-size: 14px;
  }
  
  .log-actions {
    gap: 4px;
  }
  
  .log-actions .el-button {
    padding: 6px 10px;
    font-size: 12px;
  }
}

@media (min-width: 1440px) {
  .system-settings-center {
    padding: 50px 30px;
    max-width: 1600px;
  }
  
  .settings-title {
    font-size: 36px;
  }
  
  .settings-avatar {
    width: 90px;
    height: 90px;
    font-size: 36px;
  }
}

@media (min-width: 1920px) {
  .system-settings-center {
    padding: 60px 40px;
    max-width: 1800px;
  }
  
  .settings-title {
    font-size: 40px;
  }
  
  .settings-avatar {
    width: 100px;
    height: 100px;
    font-size: 40px;
  }
}

/* 滚动条样式 */
.system-settings-bg::-webkit-scrollbar {
  width: 8px;
}

.system-settings-bg::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.system-settings-bg::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.system-settings-bg::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>